#!/usr/bin/env bash

# resolve shell-specifics
case "$(echo "$SHELL" | sed -E 's|/usr(/local)?||g')" in
    "/bin/zsh")
        RCPATH="$HOME/.zshrc"
        SOURCE="${BASH_SOURCE[0]:-${(%):-%N}}"
    ;;
    *)
        RCPATH="$HOME/.bashrc"
        if [[ -f "$HOME/.bash_aliases" ]]; then
            RCPATH="$HOME/.bash_aliases"
        fi
        SOURCE="${BASH_SOURCE[0]}"
    ;;
esac

# get base dir regardless of execution location
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
    DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
    SOURCE="$(readlink "$SOURCE")"
    [[ "$SOURCE" != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done
SOURCE=$([[ "$SOURCE" = /* ]] && echo "$SOURCE" || echo "$PWD/${SOURCE#./}")
basedir=$(dirname "$SOURCE")
gitcmd="git -c commit.gpgsign=false"

source "$basedir/scripts/functions.sh"

"$basedir"/scripts/requireDeps.sh || exit 1

failed=0
case "$1" in
    "rb" | "rbp" | "rebuild")
    (
        set -e
        cd "$basedir"
        scripts/rebuildPatches.sh "$basedir" $2 || exit 1
    ) || failed=1
    ;;
    "rbf" | "rbfull")
    (
        set -e
        cd "$basedir"
        scripts/rebuildPatches.sh "$basedir" "nofilter" || exit 1
    ) || failed=1
    ;;
    "p" | "patch")
    (
        set -e
        cd "$basedir"
        scripts/build.sh "$basedir" || exit 1
    ) || failed=1
    ;;
    "j" | "jar")
    (
        set -e
        cd "$basedir"
        scripts/build.sh "$basedir" "--jar" || exit 1
    ) || failed=1
    ;;
    "b" | "build")
    (
        set -e
        cd "$basedir"
        scripts/build.sh "$basedir" || exit 1
        (cd Paper-API ; mvn clean install) || exit 1
        (cd Paper-MojangAPI ; mvn clean install) || exit 1
        (cd Paper-Server ; mvn clean package) || exit 1
        echo "Paper jar successfully built"
        ls -la Paper-Server/target/paper*.jar
    ) || failed=1
    ;;
    "i" | "install")
    (
        set -e
        cd "$basedir"
        scripts/build.sh "$basedir" || exit 1
        mvn clean install || exit 1
        echo "Paper jar successfully built and installed to local repo"
    ) || failed=1
    ;;
    "pc" | "paperclip")
    (
        set -e
        cd "$basedir"
        scripts/paperclip.sh "$basedir" || exit 1
    ) || failed=1
    ;;
    "make")
    (
        if [[ "$2" = "bacon" ]] ; then
            set -e
            cd "$basedir"
            scripts/build.sh "$basedir" "--jar"
        fi
    )
    ;;
    "m" | "mcdev")
    (
        set -e
        cd "$basedir"
        scripts/makemcdevsrc.sh "$basedir"
    )
    ;;
    "t" | "test" | "testserver")
    (
        cd "$basedir"
        shift
        scripts/testServer.sh "$basedir" "$@"
    )
    ;;
    "td" | "testdir")
        cd "${PAPER_TEST_DIR:-$basedir/work/test-server}"
    ;;
    "u" | "up" | "upstream")
    (
        cd "$basedir"
        scripts/upstreamMerge.sh "$basedir" "$2"
    )
    ;;
    "cu" | "commitup" | "commitupstream" | "upc" | "upcommit" | "upstreamcommit")
    (
        cd "$basedir"
        shift
        scripts/upstreamCommit.sh "$@"
    )
    ;;
    "r" | "root")
        cd "$basedir"
    ;;
    "a" | "api")
        cd "$basedir/Paper-API"
    ;;
    "s" | "server")
        cd "$basedir/Paper-Server"
    ;;
    "c" | "clean")
        rm -rf Paper-API
        rm -rf Paper-Server
        rm -rf work
        echo "Cleaned build files"
    ;;
    "con" | "continue")
        if [ -d ".git/rebase-apply" ]; then
            git -c commit.gpgsign=false am --continue
        elif [ -d ".git/rebase-merge" ]; then
            git -c commit.gpgsign=false rebase --continue
        fi
    ;;
    "e" | "edit")
        case "$2" in
            "s" | "server")
            mkdir -p "$basedir/work/Temp"
            echo "$basedir/Paper-Server" > "$basedir/work/Temp/PAPER_LAST_EDIT"
            cd "$basedir/Paper-Server"
            (
                set -e

                paperstash
                $gitcmd rebase -i upstream/upstream
                paperunstash
            )
            ;;
            "a" | "api")
            mkdir -p "$basedir/work/Temp"
            echo "$basedir/Paper-API" > "$basedir/work/Temp/PAPER_LAST_EDIT"
            cd "$basedir/Paper-API"
            (
                set -e

                paperstash
                $gitcmd rebase -i upstream/upstream
                paperunstash
            )
            ;;
            "c" | "continue")
            cd "$( < "$basedir/work/Temp/PAPER_LAST_EDIT")"
            rm -f "$basedir/work/Temp/PAPER_LAST_EDIT"
            (
                set -e

                $gitcmd add .
                $gitcmd commit --amend
                $gitcmd rebase --continue

                cd "$basedir"
                scripts/rebuildPatches.sh "$basedir"
            )
            ;;
            *)
                echo "You must edit either the api or server."
            ;;
        esac
    ;;
    "setup")
        if [[ -f "$RCPATH" ]] ; then
            NAME="paper"
            if [[ ! -z "${2+x}" ]] ; then
                NAME="$2"
            fi
            (grep "alias $NAME=" "$RCPATH" > /dev/null) && (sed -i "s|alias $NAME=.*|alias $NAME='. $SOURCE'|g" "$RCPATH") || (echo "alias $NAME='. $SOURCE'" >> "$RCPATH")
            alias "$NAME=. $SOURCE"
            echo "You can now just type '$NAME' at any time to access the paper tool."
        else
          echo "We were unable to setup the paper build tool alias: $RCPATH is missing"
        fi
    ;;
    *)
        echo "PaperMC build tool command. This provides a variety of commands to build and manage the PaperMC build"
        echo "environment. For all of the functionality of this command to be available, you must first run the"
        echo "'setup' command. View below for details. For essential building and patching, you do not need to do the setup."
        echo ""
        echo " Normal commands:"
        echo "  * rb, rebuild         | Rebuild patches, can be called from anywhere."
        echo "  * p, patch            | Apply all patches to the project without building it. Can be run from anywhere."
        echo "  * j, jar              | Apply all patches and build the project, paperclip.jar will be output. Can be run from anywhere."
        echo "  * i, install          | Build and install paper into the local repo. Can be run from anywhere."
        echo "  * m, mcdev            | Setup decompiled sources for non-modified NMS files to be imported into an IDE. Can be run from anywhere."
        echo "  * u, up, upstream     | Updates the submodules used by Paper to their latest upstream versions."
        echo "  * upc, upstreamcommit | Creates the correctly-formatted upstream commit after updating upstream."
        echo "  * c, clean            | Removes all generated files, Paper-API, Paper-Server, and work."
        echo "  * t, testserver       | Run the test server with the set of plugins Paper uses as a basis for server tests."
        echo "  * con, continue       | Shortcut command for running git am --continue, or git rebase --continue."
        echo ""
        echo " These commands require the setup command before use:"
        echo "  * r, root             | Change directory to the root of the project."
        echo "  * a. api              | Move to the Paper-API directory."
        echo "  * s, server           | Move to the Paper-Server directory."
        echo "  * td, testdirectory   | Move to the test-server directory."
        echo "  * e, edit             | Use to edit a specific patch, give it the argument \"server\" or \"api\""
        echo "                        | respectively to edit the correct project. Use the argument \"continue\" after"
        echo "                        | the changes have been made to finish and rebuild patches. Can be called from anywhere."
        echo ""
        echo "  * setup               | Add an alias to $RCPATH to allow full functionality of this script. Run as:"
        echo "                        |     . ./paper setup"
        echo "                        | After you run this command you'll be able to just run 'paper' from anywhere."
        echo "                        | The default name for the resulting alias is 'paper', you can give an argument to override"
        echo "                        | this default, such as:"
        echo "                        |     . ./paper setup example"
        echo "                        | Which will allow you to run 'example' instead."
    ;;
esac

unset RCPATH
unset SOURCE
unset basedir
unset -f color
unset -f colorend
unset -f paperstash
unset -f paperunstash
if [[ "$failed" == "1" ]]; then
	unset failed
	false
else
	unset failed
	true
fi
